<template>
  <div>
    <bread-crumb
      class="bread-crumb-padding"
      :list="breadCrumb"
      :user="true"
    ></bread-crumb>
    <div class="user-main-box">
      <user-tab-list :list="tablist"></user-tab-list>
      <div class="form-input-area" style="position: relative">
        <Spin :withIcon="true" v-if="loading"></Spin>

        <div class="flx-row-bw-s">
          <div class="left-area" style="width: 130%">
            <div
              class="submit-button-style-first f-14 c-o f-w-600"
              style="cursor: pointer"
              @click="showSelectDomain"
            >
              从我的域名列表选择域名
            </div>
            <div class="flx-row-s-s div-line" style="margin-top: 20px">
              <div class="long-name">出售域名</div>
              <div style="width: 100%; position: relative">
                <Input
                  v-model="dnText"
                  wrap="hard"
                  type="textarea"
                  :autosize="{ minRows: 5, maxRows: 10 }"
                  @on-keyup="getDNNumber"
                  @on-blur="getAvailableDN"
                  placeholder="每行1个域名，可按Enter键进行换行，最多500个域名"
                />
                <span class="c-g number-tips">{{ dnNumber }}/500</span>
              </div>
            </div>
            <div class="agreement" style="margin-left: 100px">
              <Checkbox v-model="agreement">我已阅读并同意遵守</Checkbox>
              <span class="o-form-font-button" @click="agreementModel"
                >《{{ content1.name }}》</span
              >
              <span class="o-form-font-button" @click="privacyModel"
                >《{{ content2.name }}》</span
              >
            </div>
            <div class="flx-row-s-c">
              <div
                class="
                  user-strong-button
                  submit-button-style submit-button-style-first
                "
                @click="fixSubmitEvent"
              >
                上架出售
              </div>
              <div
                class="user-normal-button submit-button-style"
                style="margin-left: 24px"
                @click="fixCancel"
              >
                取消
              </div>
            </div>

            <div
              class="remind-area flx-col submit-button-style-first"
              style="margin-top: 20px"
            >
              <span class="c-o f-w-600">温馨提示：</span>
              <span class="c-black pub-m-t-14">
                1、发布出售的域名仅支持本站管理的域名。
              </span>
              <span class="c-black">
                2、域名交易信息不得包含任何违法、违规内容，一经发现即刻下架，并对违规账户做出相应处理。
              </span>
              <span class="c-black">
                3、禁止用户自拍自卖，平台有权对此种情况下的违规用户做出相应处理。
              </span>
            </div>
          </div>
          <div
            class="remind-area flx-col pub-m-l-40 pub-m-t-40 f-14"
            style="margin-bottom: 20px"
          >
            <span class="c-o f-w-600">一口价规则：</span>
            <span class="c-black pub-m-t-14"
              >卖家固定价格出售，买家付款交易立即完成{{
                parseFloat($store.state.user.domainFixPriceRate) === 0
                  ? "免手续费"
                  : `手续费${$store.state.user.domainFixPriceRate}%`
              }}，最低1元。出售周期：长期、六个月、三个月、一个月、七天，若域名在出售期间过期，则会在域名过期当日自动下架。</span
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出层选择域名 -->
    <commonModal
      :className="'select-domain-modal'"
      :title="'选择域名'"
      :show.sync="showBidding2"
      :isMask="false"
      :width="1000"
      @confirmEvent="selectConfirmEvent"
      @cancelEvent="cancelEvent"
    >
      <template #content>
        <div style="height: 420px; overflow-y: auto">
          <div class="filter-line b-b-d flx-row-s-c">
            <span class="item-name">域名状态</span>
            <span
              v-for="(item, index) in classify"
              :key="index"
              class="select-item"
              :class="[index == classifySelect ? 'active' : 'normal']"
              style="margin-right: 40px"
              @click="selectStatusEvent(index)"
            >
              {{ item }}
            </span>
          </div>
          <div class="filter-line b-b-d flx-row-s-c">
            <span class="item-name">实名认证</span>
            <Select v-model="authStatus" style="width: 150px">
              <Option
                v-for="(item, index) in authStatusList"
                :value="index"
                :key="item"
                >{{ item }}</Option
              >
            </Select>
            <span
              class="item-name pub-m-l-40"
              style="width: 147px; text-align: right"
              >注册/转入时间</span
            >
            <Input
              v-model.trim="startCreatedTime"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
            <div class="two-input-middle"></div>
            <Input
              v-model.trim="endCreatedTime"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
          </div>
          <div class="filter-line b-b-d flx-row-s-c">
            <span class="item-name">域名品类</span>
            <Cascader
              v-model="composition"
              :data="compositionList"
              :render-format="format"
              style="width: 180px"
              @on-change="cascaderChange"
            ></Cascader>
            <span class="item-name pub-m-l-50">自动续费</span>
            <Select v-model="autoRenew" style="width: 150px">
              <Option
                v-for="(item, index) in autoRenewList"
                :value="index"
                :key="item"
                >{{ item }}</Option
              >
            </Select>
            <span class="item-name" style="width: 147px; text-align: right"
              >过期时间</span
            >
            <Input
              v-model.trim="startExpireTime"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
            <div class="two-input-middle"></div>
            <Input
              v-model.trim="endExpireTime"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
          </div>
          <div class="filter-line b-b-d flx-row-s-c">
            <span class="item-name">域名后缀</span>
            <Select v-model="domainSuffixs" style="width: 150px">
              <Option
                v-for="item in domainSuffixList"
                :value="item.suffix"
                :key="item.suffix"
                >{{ item.suffix }}</Option
              >
            </Select>
            <span class="item-name" style="width: 147px; text-align: right"
              >域名长度</span
            >
            <Input
              v-model.trim="startLen"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
            <div class="two-input-middle"></div>
            <Input
              v-model.trim="endLen"
              placeholder=""
              maxlength="30"
              style="width: 120px"
            />
          </div>
          <div
            class="filter-line b-b-d flx-row-s-s pub-p-t-15"
            style="margin-bottom: 5px; height: 68px"
          >
            <span
              class="item-name pub-m-t-6"
              style="width: 100px; text-align: right"
              >域名</span
            >
            <textarea
              placeholder="批量请换行分隔"
              class="dmTextarea"
              style="overflow-y: auto; z-index: 200; top: 0; width: 150px"
              name="domain"
              @focus="dmName = true"
              @blur="dmName = false"
              :class="dmName ? 'dmTyping' : ''"
              v-model.trim="domain"
            ></textarea>
            <CheckboxGroup
              v-model="nameLike"
              style="margin-left: 20px"
              class="pub-m-t-8"
            >
              <Checkbox class="radio-mg-r-20" label="0">开头</Checkbox>
              <Checkbox class="radio-mg-r-20" label="1">结尾</Checkbox>
            </CheckboxGroup>
            <div
              class="user-strong-button line-button-size"
              style="margin: 0 10px 0 30px"
              @click="searchEvent"
            >
              搜索
            </div>
            <div
              class="user-normal-button line-button-size"
              @click="searchClearEvent"
            >
              重置
            </div>
          </div>
          <!-- 表格 -->
          <pushDomainTable
            :list="domianList"
            :loading="tableLoading"
            :pageData="pageData"
            @pageChange="pageChange"
          />
        </div>
      </template>
    </commonModal>
    <!-- 弹出层上架出售确认 -->
    <commonModal
      ref="putModal"
      :class-name="'select-domain-modal'"
      :title="'上架出售确认'"
      :show.sync="showPut"
      :loading.sync="showPutLoading"
      :is-mask="false"
      :width="1000"
      :closable="false"
      :is-s-m-s="modalSMS"
      @confirmEvent="selectConfirmEvent"
      @cancelEvent="cancelEvent(2)"
    >
      <template #content>
        <div style="height: 320px; overflow-y: auto">
          <putTable
            :list.sync="list"
            :total="dnSet.size"
            :page-data="pageData2"
            @remove="removePutData"
            @update="updatePutData"
            @pageChange="putPageChange"
            @pageSizeChange="putPageSizeChange"
          />
        </div>
      </template>
    </commonModal>
    <agreeRuleModal
      :show.sync="ruleModelShow"
      :content="ruleContent"
      :title="ruleTitle"
    ></agreeRuleModal>
    <dnSellResultModal
      title="域名出售结果"
      :show.sync="showResult"
      :sucList="resultList"
    ></dnSellResultModal>
  </div>
</template>

<script>
import { debounce, trimStr } from "@/utils/format";
import storage from "@/utils/storage";
import { getBottom, fixSubmit } from "@/api/data";
import { agreement } from "@/api/user";
import { domainTypes, domainSuffix } from "@/utils/publicData";
import { domainPageList } from "@/api/bidding";
// import tradeRules from "@/static/tradeRules";
// import partnerTradeRules from "@/static/partnerTradeRules";
export default {
  name: "VipTransferOutForm",
  components: {
    agreeRuleModal: () => import("_c/modal/agreeRuleModal/agreeRuleModal.vue"),
    commonModal: () => import("_c/modal/commonModal/index"),
    pushDomainTable: () => import("_c/table/pushDomainTable"),
    putTable: () => import("_c/table/putTable"),
    dnSellResultModal: () =>
      import("_c/modal/dnSellResultModal/dnSellResultModal.vue"),
  },
  data() {
    return {
      dmName: false,
      loading: false,
      breadCrumb: [{name: "管理中心"},{ name: "我是卖家" }, { name: "出售域名" }],
      tablist: [
        {
          name: "出售域名",
          to: "/user/dnsell",
        },
      ],
      text: "",
      // 表单数据
      dnText: "",
      dnNumber: 0,
      dnSet: new Set(),

      // 选择域名=======================================
      // 选择标的遮罩层
      showBidding2: false,
      compositionList: [],
      composition: [],
      domainCategory: "",
      domainStructure: "",
      classify: ["全部域名", "30天内到期", "已到期"],
      classifySelect: 0,
      authStatus: -1,
      authStatusList: ["未认证", "认证中", "认证成功", "认证失败"],
      // 注册转入开始时间
      startCreatedTime: "",
      // 注册转入结束时间
      endCreatedTime: "",
      // 开始过期时间
      startExpireTime: "",
      // 结束过期时间
      endExpireTime: "",
      // 自动续费
      autoRenew: -1,
      // 自动续费数据
      autoRenewList: ["已开启自动续费", "未开启自动续费"],
      // 域名后缀
      domainSuffixs: -1,
      // 域名后缀数据
      domainSuffixList: [],
      // 开始长度
      startLen: "",
      // 结束长度
      endLen: "",
      // 模板
      template: -1,
      // 模板数据
      templateList: [],
      // 搜索域名
      domain: "",
      // 开头结尾
      nameLike: [],
      // 域名列表
      domianList: [],
      pageData: {
        // 域名总数
        total: 0,
        // 页码
        page: 1,
        // 分页调试
        limit: 10,
      },
      // 表格加载状态
      tableLoading: false,
      // 选中域名数据
      selectList: [],
      colorType: 0,
      // 协议
      agreement: false,
      ruleModelShow: false,
      ruleContent: "",
      ruleTitle: "",
      // 上架出售
      showPutLoading: false,
      showPut: false,
      focus: false,
      list: [],
      total: 0,
      pageData2: {
        // 域名总数
        total: 0,
        // 页码
        page: 1,
        // 分页调试
        limit: 10,
      },
      // 上架出售源数据
      dataList: [],
      // 上架出售弹出层验证码
      modalSMS: true,
      content2: "",
      content1: "",

      showResult: false,
      resultList: [],
    };
  },
  created() {
    this.getagreement();
    let dnList = this.$route.params.dnList;
    if (dnList && dnList.length > 0) {
      this.dnText = dnList.join("\n");
    }
  },
  mounted() {
    if (this.$storage.getColorType()) {
      this.colorType = this.$storage.getColorType();
    } else {
      this.getBottom();
    }
  },
  methods: {
    async getagreement() {
      const data = [6, 7];
      const res = await agreement(data);
      if (res.code == 200 && res.result) {
        this.content1 = res.data[0];
        this.content2 = res.data[1];
      }
    },
    // 修改一口价数据
    updatePutData(event) {
      this.list[event.index][event.key] = event.value;
    },
    // 删除一口价数据
    removePutData(key) {
      this.dataList = this.dataList.filter((o) => o.domainName !== key);
      this.pageData2.total = this.dataList.length;
      this.list = this.dataList.slice(
        (this.pageData2.page - 1) * this.pageData2.limit,
        this.pageData2.limit * this.pageData2.page
      );
    },
    // 一口价分页
    putPageChange(val) {
      this.pageData2.page = val;

      this.list = this.dataList.slice(
        (this.pageData2.page - 1) * this.pageData2.limit,
        this.pageData2.limit * this.pageData2.page
      );
    },
    putPageSizeChange(val) {
      this.pageData2.limit = val;
      this.list = this.dataList.slice(
        (this.pageData2.page - 1) * this.pageData2.limit,
        this.pageData2.limit * this.pageData2.page
      );
    },
    async getBottom() {
      const { code, data } = await getBottom();
      if (code === 200) {
        this.colorType = data.colorType;
      }
    },
    // 函数防抖获取输入框中的域名
    getDNNumber: debounce(function () {
      let temp = this.dnText.split("\n");
      this.dnNumber = temp.filter((item) => {
        return !item.match(/^[ ]*$/);
      }).length;
    }, 200),
    // 筛选出有用域名
    getAvailableDN() {
      let temp = this.dnText.split("\n").filter((item) => {
        return !item.match(/^[ ]*$/);
      });
      let dnList = temp.map((item) => trimStr(item));
      this.dnSet = new Set(dnList);
      storage.setPushSelectDomian([...this.dnSet]);
      this.dnText = [...this.dnSet].join("\n");
      this.dnNumber = this.dnSet.size;
    },
    // 自定义显示格式
    format(labels) {
      const index = labels.length - 1;
      return labels[index];
    },
    // 关闭弹出层
    cancelEvent() {
      if (this.showBidding2) {
        let array = storage.getPushSelectDomian();
        let domainStr = array.join("\n");
        this.dnText = domainStr;
        this.showBidding2 = false;
      }
    },
    // 打开选择标的遮罩层
    showSelectDomain() {
      this.getDomainTypes();
      this.getDomainSuffix();
      // this.requestTemplateSelectList();
      this.getDomainPageList();
      this.showBidding2 = true;
    },
    // 表格分页事件
    pageChange(val) {
      this.pageData.page = val;
      this.getDomainPageList();
    },
    // 选择域名遮罩层
    async selectConfirmEvent(val) {
      if (this.showBidding2) {
        const array = this.$storage.getPushSelectDomian();
        const domainStr = array.join("\n");
        this.focus = true;
        this.dnText = domainStr;
        const temp = this.dnText.split("\n").filter((item) => {
          return !item.match(/^[ ]*$/);
        });
        const dnList = temp.map((item) => trimStr(item));
        this.dnSet = new Set(dnList);
        this.$storage.setPushSelectDomian([...this.dnSet]);
        this.dnNumber = this.dnSet.size;
        this.showBidding2 = false;
      } else if (this.showPut) {
        const incomplete = this.dataList.filter((o) => {
          return !o.price || o.price <= 0;
        });
        if (incomplete.length > 0) {
          this.$Message.warning("请填写完整信息!");
          return false;
        }
        this.showPutLoading = true;
        const reqData = this.dataList.map((o) => {
          return {
            domainName: o.domainName,
            comment: o.comment,
            price: o.price,
            timeType: o.timeType,
          };
        });
        try {
          const { code, data, result } = await fixSubmit({
            code: val,
            list: reqData,
          });
          if (code === 200 && result && data.length === 0) {
            this.$Message.success("提交成功！");
            this.dnText = "";
            this.dnNumber = 0;
            this.agreement = false;
            this.dnSet = new Set();
            this.$storage.setPushSelectDomian([]);
            this.showPut = false;
          } else {
            this.showResult = true;
            this.resultList = data;
            this.showPut = false;
          }
          this.showPutLoading = false;
        } catch (error) {
          this.showPutLoading = false;
        }
      }
    },
    // 获取选择域名类型
    async getDomainTypes() {
      let res = await domainTypes();
      this.compositionList = res;
    },
    // 获取域名后缀
    async getDomainSuffix() {
      let res = await domainSuffix();
      this.domainSuffixList = res;
    },
    // 级联选择器选择变化
    cascaderChange(value) {
      let temp = value[1].split("_");
      this.domainCategory = temp[0];
      this.domainStructure = temp[1];
    },
    // // 获取模板数据
    // async requestTemplateSelectList() {
    //   const { code, data } = await getTemplateSelectList({ type: 0 });
    //   if (code === 200) {
    //     this.templateList = data;
    //   }
    // },
    // 遮罩层域名筛选
    async getDomainPageList() {
      let domain = this.domain.replace(/\n/g, ",");
      let params = {};
      this.classifySelect > 0 && (params.type = this.classifySelect - 1);
      this.authStatus != -1 && (params.authStatus = this.authStatus);
      this.startCreatedTime &&
        (params.startCreatedTime = this.startCreatedTime);
      this.endCreatedTime && (params.endCreatedTime = this.endCreatedTime);
      this.domainCategory && (params.domainCategory = this.domainCategory);
      this.domainStructure && (params.domainStructure = this.domainStructure);
      this.autoRenew != -1 && (params.isAutoRenew = this.autoRenew);
      this.startExpireTime && (params.startExpireTime = this.startExpireTime);
      this.endExpireTime && (params.endExpireTime = this.endExpireTime);
      this.domainSuffixs != -1 && (params.domainSuffix = this.domainSuffixs);
      this.template != -1 && (params.templateId = this.template);
      this.startLen && (params.startLen = this.startLen);
      this.endLen && (params.endLen = this.endLen);
      this.domain && (params.name = domain);
      params.page = this.pageData.page;
      params.limit = this.pageData.limit;
      this.nameLike.length === 1 &&
        (params.nameLike = parseInt(this.nameLike[0]));
      this.tableLoading = true;
      const { code, data } = await domainPageList(params);
      this.tableLoading = false;
      if (code === 200 && data) {
        this.domianList = data.list;
        this.pageData.total = data.total;
      }
    },
    selectStatusEvent(val) {
      this.classifySelect = val;
      this.getDomainPageList();
    },
    // 搜索确定事件
    searchEvent() {
      this.getDomainPageList();
    },
    searchClearEvent() {
      this.composition = [];
      this.classifySelect = -1;
      this.authStatus = -1;
      this.startCreatedTime = "";
      this.endCreatedTime = "";
      this.domainCategory = "";
      this.domainStructure = "";
      this.autoRenew = -1;
      this.startExpireTime = "";
      this.endExpireTime = "";
      this.domainSuffixs = -1;
      this.template = -1;
      this.startLen = "";
      this.endLen = "";
      this.domain = "";
      this.page = 1;
      this.limit = 10;
      this.nameLike = [];
      this.getDomainPageList();
    },
    // 提交一口价
    fixSubmitEvent() {
      if (!this.dnText) {
        this.$Message.warning("请输入要上架的域名！");
        return false;
      }
      if (!this.agreement) {
        this.$Message.warning("请仔细阅读并勾选！");
        return false;
      }
      // 初始化输入框的数据
      const temp = this.dnText.split("\n").filter((item) => {
        return !item.match(/^[ ]*$/);
      });
      this.dataList = temp.map((o) => {
        const baseData = o.split("|");
        return {
          id: new Date().getTime(),
          domainName: baseData[0],
          timeType: 1,
          price: baseData.length >= 2 ? baseData[1] : "",
          comment: baseData.length >= 3 ? baseData[2] : "",
        };
      });
      // 分页数据
      this.list = this.dataList.slice(
        (this.pageData2.page - 1) * this.pageData2.limit,
        this.pageData2.limit * this.pageData2.page
      );
      this.pageData2.total = this.dataList.length;
      // 保存源数据
      this.showPut = true;
    },
    // 取消提交
    fixCancel() {
      this.agreement = false;
      this.dnText = "";
      this.dnNumber = 0;
      this.dnSet = new Set();
      this.dataList = [];
      this.list = [];
      this.pageData2.total = 0;
      this.$storage.setPushSelectDomian([]);
    },
    agreementModel() {
      this.ruleModelShow = true;
      this.ruleTitle = this.content1.name;
      this.ruleContent = this.content1.content;
    },
    privacyModel() {
      this.ruleModelShow = true;
      this.ruleTitle = this.content2.name;
      this.ruleContent = this.content2.content;
    },
  },
  destroyed() {
    storage.setPushSelectDomian([]);
  },
};
</script>

<style lang="scss" scoped>
.form-input-area {
  padding: 30px 20px 60px;
  .long-name {
    min-width: 70px;
  }
  .submit-button-style-first {
    margin-left: 100px;
  }
  .remind-area {
    background: #f6f7fa;
    padding: 15px 21px 37px;
    border-radius: 10px;
    font-size: 14px;
    .c-black {
      line-height: 30px;
    }
  }

  .number-tips {
    position: absolute;
    bottom: 10px;
    right: 20px;
  }
  .agreement {
    margin-top: 20px;
    margin-left: 100px;
    margin-bottom: 20px;
  }
}
</style>
